package com.company.project.component.shiro.auth;

import com.company.project.dao.*;
import com.company.project.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lzp
 * Date: 2017/11/7
 * Time: 10:20
 * function:
 */
public class AuthRealm extends AuthorizingRealm
{

    @Autowired
    UUserMapper uUserMapper;
    @Autowired
    URoleMapper uRoleMapper;
    @Autowired
    UUserRoleMapper uUserRoleMapper;
    @Autowired
    URolePermissionMapper uRolePermissionMapper;
    @Autowired
    UPermissionMapper uPermissionMapper;

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        String password = new String(utoken.getPassword());

        UUser uUser = new UUser();
        uUser.setNickname(username);
        uUser.setPswd(password);
        UUser uUserRs = uUserMapper.selectOne(uUser);
        if(uUser == null)
        {
            throw new AccountException("用户名或密码错误");
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user" , uUserRs);
        return new SimpleAuthenticationInfo(uUserRs , utoken.getPassword() , this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码

    }


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal)
    {

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        UUser uUser = (UUser) session.getAttribute("user");

        Set<String> roles = new HashSet<>();
        Set<String> permissions=new HashSet<>();
        List<Map> list = uUserMapper.getInfoByUser(uUser);
        for(Map mp : list)
        {
            String url = (String) mp.get("url");
            String roleType = (String) mp.get("type");
            if(StringUtils.isNotEmpty(url))
                permissions.add(url);
            if(StringUtils.isNotEmpty(roleType))
                roles.add(roleType);
        }

        info.addRoles(roles);
        info.addStringPermissions(permissions);//将权限放入shiro中.
        return info;

    }

}